// 运行时配置

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
import { getMenuCacheSync, getMenuTree } from '@/services/menuCache';
import { backMenuToMenuData, backMenuToRoutes } from '@/utils/menu';
import { RunTimeLayoutConfig } from '@@/plugin-layout/types';
import type { RuntimeConfig } from '@umijs/max';
import { history } from '@umijs/max';
import { message } from 'antd';

export async function getInitialState(): Promise<{ name: string }> {
  const backFlat = await getMenuTree();
  return {
    name: 'ant-plus-perm',
    backFlat,
  };
}

export const patchClientRoutes: RuntimeConfig['patchClientRoutes'] = async ({
  routes,
}) => {
  const backFlat = await getMenuTree(); // 同步读
  const dynamicRoutes = backMenuToRoutes(backFlat);
  const layoutRoot = routes.find((r: any) => r.isLayout) || routes[1];
  if (layoutRoot) layoutRoot.children = [...layoutRoot.children, ...dynamicRoutes];
};

export const layout: RunTimeLayoutConfig = ({
  initialState,
  setInitialState,
}) => {
  return {
    logo: '/images/logo.png', // 左上角logo
    title: 'ant-plus-permission',
    // pre: location.pathname === '/login' ? true : false,
    menu: {
      locale: false,
      params: { initialState },
      request: async (params, defaultMenuData) => {
        const backFlat = getMenuCacheSync();
        const staticNodes = [
          { path: '/home', name: '首页', icon: 'Home' },
          { path: '/access', name: '权限演示', icon: 'Lock' },
          { path: '/table', name: 'CRUD 示例', icon: 'Table' },
        ];
        const dynamicMenuData = backMenuToMenuData(backFlat);
        return [...staticNodes, ...dynamicMenuData];
      },
    },
  };
};

const TOKEN_EXPIRE = 401;

export const request: RuntimeConfig['request'] = {
  baseURL: 'http://localhost:7001',
  timeout: 10000,
  // ❶ 用拦截器设置 headers / credentials
  requestInterceptors: [
    (url, options) => {
      (options as any).credentials = 'include'; // 带 cookie
      const token = localStorage.getItem('token');
      if (token) {
        (
          options.headers as Record<string, string>
        ).Authorization = `Bearer ${token}`;
      }
      return { url, options };
    },
  ],

  // ❷ 响应拦截 & 全局错误
  responseInterceptors: [
    (response) => {
      const data = response.data;
      if (data?.status !== 200 && data?.message) {
        message.error(data.message);
      }
      return response;
    },
  ],

  // ❸ 自动刷新 token
  errorConfig: {
    errorHandler: async (error: any) => {
      const { response } = error;
      if (response?.status === TOKEN_EXPIRE) {
        const refreshToken = localStorage.getItem('refreshToken');
        if (!refreshToken) {
          message.error('登录已过期，请重新登录');
          history.replace('/user/login');
          return Promise.reject(error);
        }
        try {
          const { token: newToken } = await (global as any).umiRequest.post(
            '/api/refresh',
            { refreshToken },
          );
          localStorage.setItem('token', newToken);
          const cfg = error.request;
          (
            cfg.headers as Record<string, string>
          ).Authorization = `Bearer ${newToken}`;
          return (global as any).umiRequest(cfg.url, cfg);
        } catch {
          message.error('刷新令牌失败，请重新登录');
          history.replace('/user/login');
          return Promise.reject(error);
        }
      }
      message.error(response?.data?.message || '网络错误');
      return Promise.reject(error);
    },
  },
};
